﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using ZBJF.Warranty.Common.Common;

namespace ZBJF.Warranty.WebApiSite.Filter
{
    public abstract class BaseAuthenticationAttribute : ActionFilterAttribute
    {

        /// <summary>
        /// Occurs before the action method is invoked.
        /// </summary>
        /// <param name="actionContext">The action context</param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {

            try
            {
                //获取Asp.Net对应的Request
                var request = ((HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).Request;

                NameValueCollection getCollection = request.QueryString;//此签名要求Partner及Sign均通过QueryString传递

                if (getCollection == null || getCollection.Count <= 0)
                {
                    if (request.Url != null)
                    {
                        var seq = request.Url.Segments;
                        getCollection = new NameValueCollection
                        {
                            { SecuritySignHelper.Channel, seq[seq.Length - 6].Trim('/') },
                            //{ SecuritySignHelper.VendorID, appConfig.CtripVendorID },
                            { SecuritySignHelper.Version, seq[seq.Length - 4].Trim('/') },
                            { SecuritySignHelper.TimeStamp, seq[seq.Length - 3].Trim('/') },
                            { SecuritySignHelper.Sign, seq[seq.Length - 2].Trim('/') },
                            { SecuritySignHelper.Key, seq[seq.Length - 1].Trim('/') },
                        };

                    }
                }
                if (getCollection != null && getCollection.Count > 0)
                {
                    //string vendorID = getCollection[SecuritySignHelper.VendorID];
                    string version = getCollection[SecuritySignHelper.Version];
                    string channel = getCollection[SecuritySignHelper.Channel];
                    string timeStamp = getCollection[SecuritySignHelper.TimeStamp];
                    string sign = getCollection[SecuritySignHelper.Sign];
                    string keyValue = getCollection[SecuritySignHelper.Key];

                    string vendorID = this.GetVendorID(keyValue);
                    string secrectKey = this.GetSecrectKey(keyValue);

                    var vSign =
                        SecuritySignHelper.GetMD5_32(string.Format("{0}{1}{2}{3}{4}{5}", vendorID, version,
                            channel, timeStamp, secrectKey,
                            request.ContentLength));
                    if (string.Equals(sign, vSign, StringComparison.OrdinalIgnoreCase))
                    {
                        //验证通过,执行基类方法
                        base.OnActionExecuting(actionContext);
                        return;
                    }
                }
                //此处暂时以401返回，可调整为其它返回
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                //actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            }
            catch (Exception ex)
            {
                CommonMethod.WriteLogs("Error：" + ex.Message + "\r\n" + ex.Message + ex.StackTrace);

            }
        }

        /// <summary>
        /// 获取合作号对应的合作Key,如果未能获取，则返回空字符串或者null
        /// </summary>
        /// <param name="partner"></param>
        /// <returns></returns>
        protected abstract string GetSecrectKey(string keyValue);
        /// <summary>
        /// 获取合作号对应的合作Key,如果未能获取，则返回空字符串或者null
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        protected abstract string GetVendorID(string keyValue);
    }
}